import {login,loginout,autoLogin} from 'api/api';
import router from 'router/router';
import { whiteRouter } from '../../util/config';
export default{
    state:{
       userInfo:{},
       token:localStorage.getItem('sph_token')
    },
    mutations:{
        getUserInfo(state,userInfo){
            state.userInfo=userInfo
        }
    },
    actions:{
        //登录
      async login(store,{phone,password,redirectUrl}){
        try{
            // console.log(redirectUrl);
            const{code,data,message}=await login({phone,password})
            if(code===200){
                store.commit('getUserInfo',{
                    name:data.name,
                    userId:data.userId
                })
                localStorage.setItem('sph_token',data.token)
                await router.push(redirectUrl)
            }else{
                alert(message)
            }
            return {code}
        }catch(e){
            return Promise.reject(e)
        }
       },
       //退出登录
       async loginout(store,to=router.currentRoute){
        try{
            const{code,message}=await loginout()
            if(code===200){
               store.commit('getUserInfo',{})
                localStorage.removeItem('sph_token')
                const currentPath=to.name;
                const rootName=currentPath.split('-')[0]
                if(whiteRouter.includes(rootName)){
                   await router.push('/login')
                }else{
                    if(rootName==='shopcart'){
                        await store.dispatch('getCartList')
                    }
                }
            }else{
                alert(message)
            }
            return {code}
        }catch(e){
            return Promise.reject(e)
        }
       },
       //自动登录
       async autoLogin(store,to){
        try{
            const{code,data}=await autoLogin()
            if(code===200){
               store.commit('getUserInfo',{
                    name:data.name,
                    userId:data.id
               })
            }else{
               await store.dispatch('loginout',to)
            }
            return {code}
        }catch(e){
            return Promise.reject(e)
        }
       }
    },
    getters:{}
}